import React from 'react';
import {
    Row,
    Col,
    Table,
    Input,
    Switch,
    Button,
    Modal,
    Form,
    Tooltip,
    Icon,
    Select,
    DatePicker,
    notification
} from 'antd';
import axios from 'axios';
import intercept from '../../utils/intercept';
import { config } from 'utils';
import './less/common.less'
import ActivityRecords from './ActivityRecords'
import moment from 'moment'
const Search = Input.Search;
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const businessTypestr = ['汽车票', '定制客运', '城际约租'];
const activityTypestr = ['', '新用户首单立减', '每班车首个用户立减', '满减'];
class Activity extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            loading: false,
            pagination: {
                current: 1,
                pageSize: 10
            },
            onChange: this.onChange,
            keyword: '',
            activityid: 0,
            visible: false,
        };
    };
    componentDidMount() {
        this.getActivitys({ page: 1 });
    };
    search(value) {
        this.setState({ keyword: value });
        this.getActivitys({ keyword: value });
    }
    onChange = (pagination, filters, sorter) => {
        this.getOrderInfo({
            sortField: sorter.field,
            sortOrder: sorter.order,
            page: pagination.current,
            keyword: this.state.keyword,
            ...filters
        });
    };
    getActivitys = (params = {}) => {
        const token = sessionStorage.getItem("token");
        this.setState({ loading: true });
        var keyword = typeof (params.keyword) === "undefined"
            ? ''
            : params.keyword;
        axios
            .get(`${config.api}Marketing/GetActivityDiscount?page=${params.page}&pageSize=${this.state.pagination.pageSize}&keyword=${keyword}`, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                const pagination = {
                    ...this.state.pagination
                };
                //console.log(data);
                pagination.total = data.data.pageList.totalRows;
                pagination.current = params.page;
                this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination });

            })
            .catch(err => {
                intercept;
            })
    }
    getActivityRecords = (ev, activityid) => {
        this.refs.getActivityRecord.getActivitys({ keyword: activityid });
    }
    showAddActivityModel = () => {
        this.setState({
            visible: true
        })
    }
    handleCancel = (e) => {
        //console.log(e);
        this.setState({
            visible: false,
        });
    }
    handleReset = () => {
        this
            .props
            .form
            .resetFields();
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this
            .props
            .form
            .validateFieldsAndScroll((err, values) => {
                if (!err) {
                    const postdata = {
                        bussinessType: values.bussinessType, startDate: values.starttime, endDate: values.endtime, activityName: values.activityname,
                        activityDesc: values.activitydesc, activityType: values.activityType, minDiscount: values.mindiscount, maxDiscount: values.maxdiscount, lowestAmount: values.orderAmount,
                        isEnable: values.isvalid,activityid:values.activityid
                    }
                    //console.log('Received values of form: ', postdata);
                    const token = sessionStorage.getItem("token");
                    axios.post(`${config.api}Marketing/AddActivity`, postdata,
                        { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
                            //console.log("接口返回：",data);
                            if (data.data.result) {
                                this.openNotification("添加活动", "添加活动成功", "#108ee9");
                                this.props.form.resetFields();
                                var dataSource = this.state.dataSource;
                                if(!values.activityid){
                                    dataSource.unshift(data.data.activityDiscount);
                                    this.setState({
                                        dataSource
                                    });
                                }

                            } else {
                                this.openNotification("添加活动", data.data.errorMessage, "red");
                            }
                            this.setState({
                                visible: false
                            })
                        })
                        .catch(err => {
                            intercept;
                        })
                }
            });
    }
    openNotification = (title, desc, color) => {
        notification.open({
            message: title,
            description: desc,
            icon: <Icon type="smile-circle" style={{ color: color }} />,
        });
    };
    switchChange = (checked, activityid) => {
        const token = sessionStorage.getItem("token");
        axios.post(`${config.api}Marketing/EnableActivity`, { activityid: activityid, isEnable: checked },
            { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
                //console.log("接口返回：",data);
                if (data.data.result) {
                    this.openNotification("修改活动", `${checked ? '开启' : '关闭'}活动成功`, "#108ee9");
                } else {
                    this.openNotification("添加活动", data.data.errorMessage, "red");
                }
            })
            .catch(err => {
                intercept;
            })
    };
    editActivity = (ev, record) => {
        //console.log(record);
        this.props.form.setFieldsValue({
            bussinessType: record.businessType,
            starttime: new moment(record.startDate),
            endtime: new moment(record.endDate),
            activityname: record.activityName,
            activitydesc: record.activityDesc,
            activityType: record.activityType,
            mindiscount: record.minDiscount,
            maxdiscount: record.maxDiscount,
            orderAmount: record.lowestOrderAmount,
            isvalid: record.isValid,
            activityid:record.activityid
        });
        this.setState({
            visible: true
        })
    }
    deleteActivity = (ev,record) => {
        const token = sessionStorage.getItem("token");
        axios.post(`${config.api}Marketing/DelectActivity`, { activityid: record.activityid },
            { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
                //console.log("接口返回：",data);
                if (data.data.result) {
                    this.openNotification("删除活动", `删除活动成功`, "#108ee9");
                    const dataSource = this.state.dataSource.filter(item => item.activityid !== record.activityid);
                    this.setState({ dataSource });
                } else {
                    this.openNotification("删除活动", data.data.errorMessage, "red");
                }
            })
            .catch(err => {
                intercept;
            })
    }
    render() {
        const scroll = {
            y: 600
        };

        const columns = [
            {
                title: '业务类型',
                dataIndex: 'businessType',
                width: 150,
                render(text, record) {
                    return (
                        <span>{businessTypestr[record.businessType]}</span>
                    )
                }
            },
            {
                title: '活动名称',
                dataIndex: 'activityName',
                width: 150
            },
            {
                title: '活动类型',
                dataIndex: 'activityType',
                width: 150,
                render(text, record) {
                    return (
                        <span>{activityTypestr[record.activityType]}</span>
                    )
                }
            },
            {
                title: '开始时间',
                dataIndex: 'startDate',
                width: 150,
                render:(text,record) => {
                    return(
                        <span>{new moment(record.startDate).format('YYYY-MM-DD')}</span>
                    )
                }
            },
            {
                title: '结束时间',
                dataIndex: 'endDate',
                width: 150,
                render:(text,record) => {
                    return(
                        <span>{new moment(record.endDate).format('YYYY-MM-DD')}</span>
                    )
                }
            },
            {
                title: '活动描述',
                dataIndex: 'activityDesc',
                width: 150
            },
            {
                title: '优惠范围',
                dataIndex: 'discount',
                width: 150,
                render:(text,record) => {
                    return(
                        <span>{record.minDiscount} - {record.maxDiscount}</span>
                    )
                }
            },
            {
                title: '满X减',
                dataIndex: 'lowestOrderAmount',
                width: 150
            },
            {
                title: '是否启用',
                dataIndex: 'isValid',
                width: 150,
                render: (text, record) => {
                    return (
                        <span>
                            <Switch checkedChildren="开" unCheckedChildren="关" onChange={(checked, activityid) => { this.switchChange(checked, record.activityid) }} defaultChecked={record.isValid} />
                        </span>
                    )
                }
            }, {
                title: '操作',
                width: 150,
                key: 'action',
                render: (text, record) => {
                    return (
                        <span>
                            <a onClick={(ev, activityid) => { this.getActivityRecords(ev, text.activityid) }}>查看</a>
                            <span className="ant-divider" />
                            <a onClick={(ev, record) => { this.editActivity(ev, text) }}>编辑</a>
                            <span className="ant-divider" />
                            <a onClick={(ev, record) => { this.deleteActivity(ev, text) }}>删除</a>
                        </span>
                    )
                }
            }
        ];
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                }
            }
        };

        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <div className="orderinfo">
                    <Row gutter={8} style={{
                        marginTop: '20px'
                    }}>
                        <Col span={24}>
                            <div
                                style={{
                                    textAlign: 'center',
                                    margin: 10
                                }}>
                                <Search
                                    placeholder="请输入任意查询条件"
                                    style={{
                                        width: 600
                                    }}
                                    onSearch={value => this.search(value)} />
                                <Button type="primary" className='newadd' onClick={this.showAddActivityModel}>添加活动</Button>
                            </div>
                            <Table
                                {...this.state}
                                className='fixedheight'
                                bordered={true}
                                columns={columns}
                                scroll={scroll} />
                        </Col>
                    </Row>
                </div>
                <ActivityRecords ref="getActivityRecord" />
                <Modal
                    title="添加活动记录"
                    visible={this.state.visible}
                    footer={null}
                    width={700}
                    onCancel={this.handleCancel}>
                    <Form onSubmit={this.handleSubmit}>
                        <Row>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            业务类型
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('bussinessType', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<Select style={{ width: 120 }}>
                                        <Option value='0'>汽车票</Option>
                                        <Option value='1'>定制客运</Option>
                                        <Option value='2'>城际约租</Option>
                                    </Select>)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            开始时间
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('starttime', {
                                        rules: [
                                            {
                                                required: true,
                                                type: 'date',
                                                message: 'Please input your traderaccount!',
                                                whitespace: true,
                                                transform: (value) => { return typeof (value) === 'undefined' ? '' : value.toDate(); }
                                            }
                                        ]
                                    })(<DatePicker />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            结束时间
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('endtime', {
                                        rules: [
                                            {
                                                required: true,
                                                type: 'date',
                                                message: 'Please input your traderaccount!',
                                                whitespace: true,
                                                transform: (value) => { return typeof (value) === 'undefined' ? '' : value.toDate(); }
                                            }
                                        ]
                                    })(<DatePicker />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            活动名称
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('activityname', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            活动描述
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('activitydesc', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<TextArea />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            活动类型
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('activityType', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<Select style={{ width: 120 }}>
                                        <Option value='1'>新用户首单立减</Option>
                                        <Option value='2'>每班车首个用户立减</Option>
                                        <Option value='3'>满减</Option>
                                        <Option value='4'>赠送保险</Option>
                                    </Select>)}
                                </FormItem>
                                <FormItem
                                    label="优惠区间"
                                    {...formItemLayout}
                                >
                                    <Col span={10}>
                                        <FormItem>
                                            {getFieldDecorator('mindiscount', { rules: [{ required: true }] })(<Input style={{ width: 70, textAlign: 'center' }} placeholder="Minimum" />)}
                                        </FormItem>
                                    </Col>
                                    <Col span={3}>
                                        <Input style={{ width: 24, borderLeft: 0, pointerEvents: 'none', backgroundColor: '#fff' }} placeholder="~" disabled />
                                    </Col>
                                    <Col span={10}>
                                        <FormItem>
                                            {getFieldDecorator('maxdiscount', { rules: [{ required: true }] })(<Input style={{ width: 70, textAlign: 'center', borderLeft: 0 }} placeholder="Maximum" />)}
                                        </FormItem>
                                    </Col>
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            满X元减
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('orderAmount', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<Input />)}
                                </FormItem>
                                <FormItem
                                    {...formItemLayout}
                                    label={(
                                        <span>
                                            是否启用
                      <Tooltip title="自动填充">
                                                <Icon type="question-circle-o" />
                                            </Tooltip>
                                        </span>
                                    )}
                                    hasFeedback>
                                    {getFieldDecorator('isvalid', {
                                        rules: [
                                            {
                                                required: true,
                                                type: 'boolean',
                                                message: 'Please input your traderaccount!',
                                                whitespace: true
                                            }
                                        ]
                                    })(<Switch defaultChecked={false} />)}
                                </FormItem>
                                <FormItem
                                    style={{ visibility: 'hidden' }}
                                    hasFeedback>
                                    {getFieldDecorator('activityid', {
                                    })(<Input />)}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <FormItem className="center">
                                    <Button onClick={this.handleReset}>重置</Button>{' '}
                                    <Button type="primary" htmlType="submit">确定</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            </div>
        )
    }
}
const Activitys = Form.create()(Activity);
export default Activitys
